package org.shean.app.rssreader;

import java.text.ParseException;

import org.shean.app.rssreader.provider.SzRSSReader;
import org.shean.app.rssreader.utils.DateUtils;
import org.shean.app.rssreader.utils.RssUtils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PostViewActivity extends Activity implements 
View.OnTouchListener, View.OnClickListener{
	private WebView mPostText;
	private TextView mTitleView;
	private TextView mDateView;
	private TextView mTagView;
	private ImageView mFavoriteView;
	private LinearLayout mCommentGroup;
	private LayoutInflater mInflater;
	
	private String mTitle;
	private String mBody;
	private String mUrl;
	private String mDate;
	private boolean is_favorite;
	
	public static final String PREFS_NAME = "RSSPrefsFile";

	private static final String[] PROJECTION = new String[] {
			SzRSSReader.Posts._ID, SzRSSReader.Posts.CHANNEL_ID,
			SzRSSReader.Posts.TITLE, SzRSSReader.Posts.DESCRIPTION, SzRSSReader.Posts.IS_READ,
			SzRSSReader.Posts.LINK,SzRSSReader.Posts.IS_FAVORITE,SzRSSReader.Posts.POST_DATE};

	private long mPostID = -1;
	
	private static final int EDIT_TAG = 1;
	private static final int EDIT_COMMENT = 2;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		setContentView(R.layout.szpost_view);
		
		mPostText = (WebView) findViewById(R.id.post_body);
		mTitleView = (TextView) findViewById(R.id.subject);
		mDateView = (TextView) findViewById(R.id.publish_time);
		mTagView = (TextView) findViewById(R.id.tag);
		mFavoriteView =(ImageView) findViewById(R.id.favorite);
		mCommentGroup = (LinearLayout) findViewById(R.id.comment_container);
		
		ImageButton previousbtn = (ImageButton)findViewById(R.id.previous);
		ImageButton nextbtn = (ImageButton)findViewById(R.id.next);
		previousbtn.setOnClickListener(this);
		nextbtn.setOnClickListener(this);
		
		mPostText.setOnTouchListener(this);
		
		mInflater = getLayoutInflater();
		
		
	}
	
	private void init()
	{
		Uri uri = getIntent().getData();
		//mCursor = managedQuery(uri, PROJECTION, null, null, null);
		//mCursor.moveToNext();
		
		Cursor c = managedQuery(uri, PROJECTION, null, null, null);
		c.moveToFirst();
		mPostID = Long.parseLong(uri.getPathSegments().get(1));
		//mChannelID = c.getLong(c.getColumnIndex(SzRSSReader.Posts.CHANNEL_ID));
		mTitle = c.getString(c.getColumnIndex(SzRSSReader.Posts.TITLE));
		mBody = c.getString(c.getColumnIndex(SzRSSReader.Posts.DESCRIPTION));
		mUrl = c.getString(c.getColumnIndex(SzRSSReader.Posts.LINK));
		
		String datestr = c.getString(c.getColumnIndex(SzRSSReader.Posts.POST_DATE));
		try {
			mDate = DateUtils.formatCompleteDate(datestr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		is_favorite = c.getInt(c.getColumnIndex(SzRSSReader.Posts.IS_FAVORITE)) == 1;
		c.close();

		ContentValues values = new ContentValues();
		values.put(SzRSSReader.Posts.IS_READ, 1);
		getContentResolver().update(getIntent().getData(), values, null, null);
	}

	@Override
	public void onResume() {
		super.onResume();
		init();
		initWithData();
	}

	
	@Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        init();
        initWithData();
	}

	public void initWithData() {
		
		TextView numbers = (TextView)findViewById(R.id.numbers);
		int currentPosition = RssUtils.sCurrentPoistion + 1;
		String numbertxt = "" + currentPosition + "/" + RssUtils.sViewList.length;
		numbers.setText(numbertxt);
		
		TextView tagedit = (TextView)findViewById(R.id.tag_edit);
		SpannableString tag_str = new SpannableString("Edit");
		Uri edit_uri = ContentUris.withAppendedId(SzRSSReader.Posts.CONTENT_URI, mPostID);
		MyEditSpan tagSpan = new MyEditSpan(edit_uri,"android.intent.action.EDIT_TAG", EDIT_TAG);
		tag_str.setSpan(tagSpan, 0, tag_str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
		tagedit.setText(tag_str);
		tagedit.setMovementMethod(LinkMovementMethod.getInstance());
		
		TextView comentedit = (TextView)findViewById(R.id.comment_edit);
		SpannableString comment_str = new SpannableString("Edit");
		MyEditSpan commentSpan = new MyEditSpan(edit_uri,"android.intent.action.EDIT_COMMENT", EDIT_COMMENT);
		comment_str.setSpan(commentSpan, 0, comment_str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
		comentedit.setText(comment_str);
		comentedit.setMovementMethod(LinkMovementMethod.getInstance());	
		
		ContentResolver cr = getContentResolver();

		String html = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body>"
			+ mBody + "</body></html>";

		mTitleView.setText(
	            Html.fromHtml(
	                "<a href=\""  +mUrl +"\">" + mTitle + "</a> "));
		mTitleView.setMovementMethod(LinkMovementMethod.getInstance());

		mDateView.setText(mDate);
		
		if(is_favorite)
			mFavoriteView.setImageResource(R.drawable.btn_star_big_on);
		else
			mFavoriteView.setImageResource(R.drawable.btn_star_big_off);
		
		mFavoriteView.setOnClickListener(this);
		
		mPostText.loadDataWithBaseURL(null, html, "text/html", "utf-8",
				"about:blank");
		
		//show tag
		showTags();
		
		//show comment
		showComments();
		

	}
	
	private void showTags()
	{
		Uri uri = ContentUris.withAppendedId(SzRSSReader.PostTags.CONTENT_URI, mPostID);
		String[] cols = new String[]{SzRSSReader.PostTags._ID, SzRSSReader.PostTags.NAME,
				SzRSSReader.PostTags.TAG_ID};
		Cursor c = this.managedQuery(uri, cols, null, null, null);
		StringBuffer tag = new StringBuffer();
		if(c.getCount() > 0)
		{
			c.moveToFirst();
			do
			{
				tag.append(c.getString(c.getColumnIndexOrThrow(SzRSSReader.PostTags.NAME)) + ",");
			}while(c.moveToNext());
		}
		else
		{
			tag.append("none");
		}

		c.close();
		mTagView.setText(tag.toString());
	}
	
	private void showComments()
	{
		Uri uri = SzRSSReader.PostComments.CONTENT_URI;
		String[] cols = new String[]{SzRSSReader.PostComments._ID, SzRSSReader.PostComments.COMMENT, SzRSSReader.PostComments.CREATE_DATE};
		String where = SzRSSReader.PostComments.POST_ID + "='" + mPostID + "'";
		Cursor c = this.managedQuery(uri, cols, where, null, null);
		
		mCommentGroup.removeAllViews();
		if(c.getCount() > 0)
		{
			c.moveToFirst();
			do
			{
				View view = mInflater.inflate(R.layout.view_comment_entry, mCommentGroup, false);
				String datestr = c.getString(c.getColumnIndexOrThrow(SzRSSReader.PostComments.CREATE_DATE));
				TextView dateview = (TextView)view.findViewById(R.id.comment_date);
				try {
					dateview.setText(DateUtils.formatCompleteDate(datestr));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				TextView commentview = (TextView)view.findViewById(R.id.comment);
				String comment = c.getString(c.getColumnIndexOrThrow(SzRSSReader.PostComments.COMMENT));
				commentview.setText(comment);
				
				mCommentGroup.addView(view);
			}while(c.moveToNext());
		}

		c.close();
	}
	
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case EDIT_TAG:
                if (resultCode == RESULT_OK) {
                	showTags();
                }
                break;
            case EDIT_COMMENT:
                if (resultCode == RESULT_OK) {
                	showComments();
                }
                break;
        }
    }
	
	private long mStartTime;
	private float mStartX;

	public boolean onTouch(View v, MotionEvent event) {
		Log.d("POSTVIEW", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Touch: " + event);
		int action = event.getAction();
		float x = event.getX();
		long time = event.getEventTime();
		
		switch(action)
		{
		case MotionEvent.ACTION_DOWN:
			mStartTime = time;
			mStartX = x;
			break;
		case MotionEvent.ACTION_UP:
			float motion = Math.abs(mStartX - x);
			long timechange = mStartTime - time;
			Log.d("POSTVIEW", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TIME CHANGE 1: " + timechange);
			if(motion < 10.0 && time - mStartTime > 800)
			{
				Log.d("POSTVIEW", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LONG CLICK!");
				if(mUrl != null && mUrl.length() > 0)
				{
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl)));
				}
			}
			else if(motion > 50.0)
			{
				if(mStartX - x > 0)
				{
					Log.d("POSTVIEW", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GO LEFT!");
					//viewPreviousPost();
				}
				else
				{
					Log.d("POSTVIEW", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GO RIGHT!");
					//viewNextPost();
				}
			}
			break;
		}
		
		return false;
	}
	
	class MyEditSpan extends URLSpan
	{
		private Uri mUri;
		private String mAction;
		private int mRequestCode;

		public MyEditSpan(Uri uri, String action, int rc)
		{
			super(uri.toString());
			mUri = uri;
			mAction = action;
			mRequestCode = rc;
		}
		
		@Override
		public void onClick(View widget) {
	        Intent intent = new Intent(mAction, mUri);
	        PostViewActivity.this.startActivityForResult(intent, mRequestCode);		
		}
		
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.favorite:
			if(is_favorite)
				mFavoriteView.setImageResource(R.drawable.btn_star_big_off);
			else
				mFavoriteView.setImageResource(R.drawable.btn_star_big_on);
			
			ContentValues values = new ContentValues();
			values.put(SzRSSReader.Posts.IS_FAVORITE, is_favorite?0:1);
			Uri uri = ContentUris.withAppendedId(SzRSSReader.Posts.CONTENT_URI, mPostID);
			getContentResolver().update(uri, values, null, null);
			
			is_favorite = !is_favorite;
			return;
		case R.id.previous:
			RssUtils.viewPrevPost(this);
			return;
		case R.id.next:
			RssUtils.viewNextPost(this);
			return;
		}
		
	}

}
